define(function(require,exports,module) {
	// require('./plug/hammer.min');
 //    require('./plug/swiper.jquery.min');
	// require('./plug/lazyload_echo');
	// require('./shop');
    var myPub = require('./public');

    var tabIndex = 0;//当前选中tab
    var start = 0
    var limit = 20;//每页展示多少条数据

    var myDate = {
    	categoryIds: [],	//库存
    	pagearr : [],		//翻页
    	falgarr : [],		//是否浏览过
    	loadOff : [],		//是否还有数据
    	WScrTop : []		//页面滚动高度
    }

    var oHScroll = $('.js_HScroll');		//水平滚动 导航和产品
    var oHScroll_Ul = oHScroll.find('ul');
    var oHScroll_Li = oHScroll.find('li');
    var oGoods_showOne = $('.js_goods_showOne')

	var oMoreBtn = $('.js_moreBtn'); 			//加载更多按钮
	var oGoods_nav = $('.js_goods_nav');
	var oSilderBox = $('.js_silderBox');
	var $window = $(window);


	var categoryName = window.location.search.split('&')[0].split('=')[1];


	var initSecondCategory = oGoods_nav.find('li[cateChecked="cateChecked"]').index();
	if(initSecondCategory != -1){
		sessionStorage.setItem(categoryName + "_index",initSecondCategory);
	}


	var indexNav = parseInt( sessionStorage.getItem(categoryName + "_index") );


	$window.resize(function() { SetUlWidth(); });
	$window.on('scroll',function() {
		myPub.throttle(addFixed,window)
	});

 	$(window).unload(function(){
 		var _index = null;
 		oHScroll_Li.each(function(i) {
			if(oHScroll_Li.eq(i).hasClass('active')) {
				_index = i
			}
		});

		myDate.WScrTop[_index] = $window.scrollTop();

    	SetSession(_index);
	});

	oGoods_showOne.css({'margin-top': oGoods_nav.height() + 6 })


    function SetUlWidth() {
    	//水平滚动li的宽度
	    var oHScroll_Li_W = oHScroll_Li.outerWidth(true);
	    oHScroll_Ul.css({
	    	'width' : oHScroll_Li_W * oHScroll_Li.length
	    });
    }


    //广告轮播
	var sTime = null;
    var oSilderImg = $('.js_silderImg');        //广告轮播框
    var oBNext = $('.js_BNext');                //下一个
    var oBPrev = $('.js_BPrev');                //上一个
    var oPagin = $('.js_pagin');                //个数点



	/**
	 * 广告轮播效果
	 * @returns
	 */
    function Swiper_indexAD(){
    	var indexSwiperAD = oSilderImg.swiper({
      	nextButton: oBNext,
    	    prevButton: oBPrev,
    	    pagination: oPagin,
    	    paginationClickable: false,
    	    preloadImages: false,
    	    lazyLoading: true,
    	    autoplay: 4000,
    	    onTouchEnd: function (swiper) {
    	        clearTimeout(sTime);
    	        sTime = setTimeout(function () {
    	        	indexSwiperAD.startAutoplay();
    	        }, 4000);
    	    },
    	});
    }



    //SetUlWidth();
	//addFixed();
	//Swiper_indexAD();
	//loadIndexDate(indexNav);
	//myPub.lazLoadingImgEcho();


    //页面执行JS的入口
	module.exports = {
        init:function(){
        	SetUlWidth();
        	addFixed();
        	Swiper_indexAD();
        	loadIndexDate(indexNav);
        	myPub.lazLoadingImgEcho();
        }
    };

    //分类导航单击事件
	oHScroll_Li.on('click',function() {
		setScrollTop();
		var index = $(this).index();

		oHScroll_Li.removeClass('active').eq(index).addClass('active');
		oGoods_showOne.find('ul').hide().eq(index).show();
		//是否加载数据
		if(myDate.falgarr[index]) {
			loadRootData(index, start, limit * (myDate.pagearr[index]+1));
		}


		var _time1 = null;
		clearTimeout(_time1);
		_time1 = setTimeout(function() {
			$window.scrollTop(myDate.WScrTop[index])
			SetSession(index)
		},300)

		//显示 是否加载按钮
		checkDate(index)
		tabIndex = index;

		oGoods_nav.removeClass('fixedDom');
	});


	//显示更多
	oMoreBtn.hammer().on('tap',function() {
		//显示加载中
		var _this = $(this);

		if(myDate.loadOff[tabIndex]) {
			myDate.pagearr[tabIndex]++;
		}


		//显示加载中
		loadRootData(tabIndex,myDate.pagearr[tabIndex],limit,function() {
			//加载按钮变化效果
			if(myDate.loadOff[tabIndex]){
				_this.show();
				$('#noMore').hide();
			}
			else{
				_this.hide();
				$('#noMore').show();
			}
			_this.siblings('.js_loadingBtn').hide().find('.icoStyle').removeClass('myRotateRefresh');

		},function() {
			_this.hide().siblings('.js_loadingBtn').show().find('.icoStyle').addClass('myRotateRefresh');
		});

		//设置临时存储
		SetSession(tabIndex)
		myPub.HamstopPropaga();
	});





    function loadIndexDate(indexNav) {

		var initSecondCategory = oGoods_nav.find('li[cateChecked="cateChecked"]').index();
		console.log(initSecondCategory);
		if(initSecondCategory != -1){
			sessionStorage.setItem(categoryName + "_index",initSecondCategory);
		}

    	//判断缓存是否有对应参数
    	if(sessionStorage.getItem(categoryName + "_index") == null) {
    		initBaseData();
    		loadRootData(tabIndex,myDate.pagearr[tabIndex],limit,function() {
    			$window.scrollTop(myDate.WScrTop[tabIndex])
    		});
    	}
    	else {
    		//导航索引
    		getSessionStorage();
    		oHScroll_Li.removeClass('active').eq(indexNav).addClass('active');
    		oGoods_showOne.find('ul').hide().eq(indexNav).show();

    		loadRootData(indexNav, start, limit * (myDate.pagearr[indexNav]+1), function() {
    			//console.log('load1--'+myDate.WScrTop[indexNav] )
    			$window.scrollTop(myDate.WScrTop[indexNav]);
				//console.log('load--'+$window.scrollTop()  )
    		});

    		checkDate(indexNav);
    	}
    }


    //检测 是否 显示加载按钮
    function checkDate(iNow) {
    	if(myDate.loadOff[iNow]) {
			$('#more').show()
			$('#noMore').hide();
		}
		else {
			$('#more').hide()
			$('#noMore').show();
		}
    }




	//初始化参数
	function initBaseData(){
		oHScroll_Li.each(function(i){
			myDate.falgarr[i] = true;//是否单击选中过
			myDate.loadOff[i] = true;//是否还有数据库
			myDate.pagearr[i] = 0;//第几页
			myDate.categoryIds[i] = oHScroll_Li.eq(i).attr('cId');
			myDate.WScrTop[i] = 0
		});
	}


	//设置本地缓存
	function getSessionStorage() {
        var _loadOff = sessionStorage.getItem(categoryName + "_loadOff");
        var _pagearr = sessionStorage.getItem(categoryName + "_pagearr");
        var _WScrTop = sessionStorage.getItem(categoryName + "_WScrTop");

		oHScroll_Li.each(function(i){
			myDate.falgarr[i] = true ;//是否单击选中过


			if(_loadOff != null && _loadOff.split(',').length > i) {
                myDate.loadOff[i] = _loadOff.split(',')[i]		//是否还有数据库
			}else {
                myDate.loadOff[i] = false;
			}


            if(_pagearr != null && _pagearr.split(',').length > i) {
                myDate.pagearr[i] = parseInt(_pagearr.split(',')[i]);
            }else {
                myDate.pagearr[i] = 0;
            }

            if(_WScrTop != null && _WScrTop.split(',').length > i) {
                myDate.WScrTop[i] = parseInt(_WScrTop.split(',')[i]);
            }else {
                myDate.WScrTop[i] = 0;
            }
			myDate.categoryIds[i] = oHScroll_Li.eq(i).attr('cId');
		});
		//  console.log(myDate);

	}


	function setBlean(obj) {
		if(obj == 'true') {
			return true
		}
		else {
			return false
		}
	}



	function SetSession(index) {
		sessionStorage.setItem(categoryName + "_index", index);
    	sessionStorage.setItem(categoryName + "_loadOff", myDate.loadOff);
    	sessionStorage.setItem(categoryName + "_pagearr", myDate.pagearr);
    	sessionStorage.setItem(categoryName + "_WScrTop", myDate.WScrTop);
   }


	/**
	 * @param tabIndex 当前选中的li下标 从0开始
	 * @param indexPage 第几页 从0开始
	 * @returns
	 */
	function loadRootData(tabIndex,indexPage,limitNum,callBack,before,over){
		var _time = null;
		var url='/category/loadOne';

		myDate.falgarr[tabIndex] = false;

		var jsonData = {
			categoryId : myDate.categoryIds[tabIndex],
			start : parseInt(indexPage) * parseInt(limitNum),
			limit: parseInt(limitNum)
		}


    	if(tabIndex == 0){
    		url= "/category/loadAll";
    	}

		G_JSON_POST(url,jsonData,function(data){
			//回调
    		if(data.length > 0){
    		    var html = "";
    			var goodsList = eval(data);
				$.each(goodsList,function(index,obj){
					if(obj.productName==null || obj.productName==undefined){
						obj.productName = "暂无规格";
					}
					html+='<li>'+
							'<a class="HBox" href="/shop/goods/view/'+obj.goodsSn+'">'+
							    '<figure>'+
							        '<img class="js_lazyImg" data-echo="'+myPub.httpImageUrl + obj.showImage + '" src="/static_v3/image/loadImg.jpg">'+
							        '<i class="tip-th" style="display: none;"></i>'+
							    '</figure>'+
							    '<aside class="priceArea VBox Bflex1">'+
							    	'<div class="Bflex1 priceArea_name">'+
							    		'<h4>'+obj.name+'</h4>'+
							    		'<p class="smallFont_tip">'+obj.title+'</p>'+
							    	'</div>'+
							    	'<div class="priceArea_price">'+
										//'<p class="smallFont_tip del">'+obj.marketPrice+'/'+obj.productName+'</p>'+
						            	'<p class="HBox BoxCenter priceAreaBox">'+
					                        '<i>￥</i>'+
					                        '<span class="goodsPrice">'+obj.salePrice+'</span>'+
					                        '<span class="goodsWeight Bflex1">/'+obj.productName+'</span>'+
						                '</p>'+
						            '</div>'+
							    '</aside>'+
							'</a>'+
							'<p class="addCar js_addCar" pId="'+obj.productId+'"><em class="icon-shopcar_small"></em></p>'+
						'</li>';


				});

    		}
    		else{
    			$('#more').hide().siblings('.js_loadingBtn').hide().find('.icoStyle').removeClass('myRotateRefresh');
				$('#noMore').show();
    		}

    		//设置记载数据的开关
    		if(sessionStorage.getItem(categoryName + "_loadOff") !== null) {
    			if( !setBlean(sessionStorage.getItem(categoryName + "_loadOff").split(',')[tabIndex]) ) {
	    			myDate.loadOff[tabIndex] = false;
	    		}
	    		else {
	    			if(goodsList == null){
						myDate.loadOff[tabIndex] = false;
					}
					else{
						myDate.loadOff[tabIndex] = true;
					}
	    		}
    		}




			oGoods_showOne.find('ul').eq(tabIndex).append(html);
			clearTimeout(_time)
			_time = setTimeout(function() {
				myPub.lazLoadingImgEcho();
				if(callBack) callBack()
			},250)


    	},function(){if(before)before()}, function() {if(over)over()});
	}



	function setScrollTop() {
		var indexNav = parseInt( sessionStorage.getItem(categoryName + "_index") );
		if(sessionStorage.getItem(categoryName + "_index") == null)  {
			indexNav = 0
		}
		myDate.WScrTop[indexNav] = $window.scrollTop();
		sessionStorage.setItem(categoryName + "_WScrTop", myDate.WScrTop);
	}


	function addFixed() {
    	$window.scrollTop() > oSilderBox.height() ? oGoods_nav.addClass('fixedDom') : oGoods_nav.removeClass('fixedDom')
    }










});